package com.changhai.diabetes.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.arcsoft.common.util.JsonUtil;
import com.changhai.diabetes.model.AjaxResultMsg;
import com.opensymphony.xwork2.Action;

public class AjaxResultUtil {
	private static Logger log = Logger.getLogger(AjaxResultUtil.class);

	public static final String HEAD_REQUEST_TYPE_PARAM = "X-Requested-With";
	public static final String HEAD_REQUEST_TYPE_AJAX = "XMLHttpRequest";

	private static final String DEFAULT_CHARSET = "utf-8";
	private static final String CONTENT_TYPE = "application/json; charset=" + DEFAULT_CHARSET;
	private static final String HEAD_ACCEPT = "Accept";

	public static void writeExcept(Throwable e, HttpServletResponse resp) throws IOException {
		resp.setContentType(AjaxResultUtil.CONTENT_TYPE);
		AjaxResultMsg msg = new AjaxResultMsg(Action.ERROR);
		msg.setMsg(e.getMessage());
		try {
			resp.getWriter().write("{ajaxMsg:" + JsonUtil.toJSON(msg) + "}");
		} catch (Exception jsonE) {
			log.error("wiret except to json-response ocurred error %s", jsonE);
		}
	}

	public static void writeAuth(HttpServletRequest hRequest, HttpServletResponse hResponse, String page_login)
			throws IOException {
		String accept = hRequest.getHeader(HEAD_ACCEPT);
		StringBuffer result = new StringBuffer(200);
		if (accept != null && accept.indexOf("text/html") != -1) {
			// AJAX PAGE request, Session overtime
			result.append("<script>").append("window.top.location.href=\"").append(hRequest.getContextPath()).append(
					page_login).append("\"").append("</script>");
		} else {
			// AJAX Data request，Session overtime
			hResponse.setContentType(CONTENT_TYPE);
			result.append("{\"fnc\":").append("window.top.location.href=\"").append(hRequest.getContextPath()).append(
					page_login).append("\"").append("}");
		}
		hResponse.getWriter().write(result.toString());
	}

	public static void writeRole(HttpServletRequest hRequest, HttpServletResponse hResponse, String page_login)
			throws IOException {
		String accept = hRequest.getHeader(HEAD_ACCEPT);
		StringBuffer result = new StringBuffer(200);
		if (accept != null && accept.indexOf("text/html") != -1) {
			// AJAX PAGE request, Session overtime
			result.append("<script>window.alert(\"Sorry,you can't access this modual\")</script>");
		} else {
			// AJAX Data request，Session overtime
			hResponse.setContentType(CONTENT_TYPE);
			result.append("{\"fnc\":").append("window.alert(\"Sorry,you can't access this modual\")").append("}");
		}
		hResponse.getWriter().write(result.toString());
	}
}
